import router from 'src/router'
import store from 'src/store'
import common from 'src/util/common'

/**
 * 路由权限判断入口
 */
router.beforeEach((to, from, next) => {
  to.meta.title && common.setTitle(to.meta.title)
  let loginKey = window.localStorage.accessToken || ''
  if (!loginKey) { // 用户是否登录过
    if (to.name !== 'login') { // 不是跳转登录页或修改密码页，统一跳转到登录页
      next({
        name: 'login'
      })
    } else {
      next()
    }
  } else {
    (async () => {
      if (to.name !== 'login' && !store.getters.getNetType) {
        let lists = await store.dispatch('setRoleData') // 获取权限列表信息
        router.options.routes.push(...lists)
        router.addRoutes(lists)
        next({...to, replace: true})
      } else {
        next()
      }
    })()
  }
})
